package com.itheima.jdbc.JDBC转账事务管理;

import com.itheima.jdbc.数据库MYSQL.util.JDBCUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBC转账事务管理 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pre1 = null;
        PreparedStatement pre2 = null;

        //获取连接
        try {
            conn = JDBCUtil.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //定义sql
            String sql1 = "update account set balance=balance-? where id=? ";
            String sql2 = "update account set balance=balance+? where id=? ";
            //获取执行sql对象
            pre1 = conn.prepareStatement(sql1);
            pre2 = conn.prepareStatement(sql2);
            pre1.setDouble(1, 500);
            pre1.setDouble(2, 1);
            pre2.setDouble(1, 500);
            pre2.setDouble(2, 2);
            //执行sql
            pre1.executeUpdate();
            //出现异常
            //int i = 3 / 0;
            pre2.executeUpdate();
            conn.commit();
            //不处理结果
            //释放资源

        } catch (Exception e) {
            try {
                System.out.println("事务管理异常....................");
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtil.colse(pre1, conn);
            JDBCUtil.colse(pre2, null);
        }

    }
}
